﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using simulatMeter.Lib;

namespace simulatMeter
{
    public partial class MeterControl : UserControl
    {

        public Config cfg = new Config();
        public ConfigItem currentitem;


        public MeterControl()
        {
            InitializeComponent();

            int cnt = cfg.ReadConfig();

            if (cnt > 0)
            {
                foreach (ConfigItem item in cfg.clist)
                {
                    this.cbNames.Items.Add(item.configName);
                    toolmenustripConfig i = new toolmenustripConfig(item.configName,item);
                    i.Click += i_Click;
                    cmsUsage.Items.Add(i);
                    if (item.Usage == true)
                    { i.Checked = true; }
                    
                } 
            }

            this.cbNames.TextChanged += cbNames_TextChanged;

            this.cbNames.SelectedIndex = 0;
            this.cbNames.Update();

            //电表管理 
            //this.dgvList.SelectionChanged += dgvList_SelectionChanged;
           // this.dgvList.CellValueChanged += dgvList_CellValueChanged;

            this.DoubleBuffered = true;
         
        }

        void i_Click(object sender, EventArgs e)
        {

            toolmenustripConfig item = (toolmenustripConfig)sender;
            if (item.Checked == true) item.Checked = false;
            else item.Checked = true;

            cfg.SaveUsage(item.item, item.Checked);


        
        }


        /// <summary>
        /// 修改其中的一个数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void dgvList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (currentitem != null && this.dgvList.CurrentRow != null)
            {
                if (this.dgvList.CurrentRow.Index >= currentitem.dis.Count) return;
                int rowindex = this.dgvList.CurrentRow.Index;

                Didata o = currentitem.dis[rowindex];
                Didata olddi = new Didata(o.SN, o.DI, o.Name, o.Len, o.Data, o.type);
                //修改一个数据项时，所有数据跟着变
                String[] values = new String[5]{
                                  this.dgvList.Rows[rowindex].Cells[0].Value.ToString(),
                                  this.dgvList.Rows[rowindex].Cells[1].Value.ToString(),
                                  this.dgvList.Rows[rowindex].Cells[2].Value.ToString(),
                                  this.dgvList.Rows[rowindex].Cells[3].Value.ToString().Replace(" ",""),
                                  this.dgvList.Rows[rowindex].Cells[4].Value.ToString()
                                   };

                this.dgvList.Rows[rowindex].Cells[3].Value = values[3];

                try
                {
                     currentitem.ChangeDIValue(values, rowindex);
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

                if (cfg.SaveDiData(currentitem, olddi,currentitem.dis[rowindex],Config.optype.Modify) < 0)
                {
                    MessageBox.Show("保存修改出错");
                }

            }
        }


        /// <summary>
        /// 点击 表格中的 一行 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void dgvList_SelectionChanged(object sender, EventArgs e)
        {
            if (currentitem != null && this.dgvList.CurrentRow != null)
            {
                if (this.dgvList.CurrentRow.Index >= currentitem.dis.Count) return;
                int index = this.dgvList.CurrentRow.Index;
                
                this.tb_DI.Text = ((currentitem.meterType == MeterType.Meter07)? currentitem.dis[index].DI32String:currentitem.dis[index].DI16String);
                this.tb_Len.Text = currentitem.dis[index].LenString;
                this.tb_Name.Text = currentitem.dis[index].Name;
                this.tb_Data.Text = currentitem.dis[index].Data;
                this.tb_type.Text = currentitem.dis[index].DataTypeString;
            }
        }

        /// <summary>
        /// 配置表修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cbNames_TextChanged(object sender, EventArgs e)
        {

            this.tb_meters.TextChanged -= tb_meters_TextChanged;
            this.dgvList.SelectionChanged -= dgvList_SelectionChanged;
            this.dgvList.CellValueChanged -= dgvList_CellValueChanged;

            this.dgvList.Rows.Clear();
            this.tb_meters.Clear();

            //加载数据项
            foreach (ConfigItem item in cfg.clist)
            {
                if (item.configName == this.cbNames.Text)
                {
                    currentitem = item;
                    this.dgvList.Rows.Clear();
                    foreach (Didata di in item.dis)
                    {
                        int index = this.dgvList.Rows.Add();
                        this.dgvList.Rows[index].Cells[0].Value = ((currentitem.meterType == MeterType.Meter07) ? di.DI32String : di.DI16String);
                        this.dgvList.Rows[index].Cells[1].Value = di.Len.ToString("d");
                        this.dgvList.Rows[index].Cells[2].Value = di.type.ToString();
                        this.dgvList.Rows[index].Cells[3].Value = di.Data;
                        this.dgvList.Rows[index].Cells[4].Value = di.Name;

                    }

                    foreach (string l in item.mlist){ this.tb_meters.AppendText(" "+l+",");}

                }

            }

            this.tb_meters.TextChanged += tb_meters_TextChanged;
            this.dgvList.CellValueChanged += dgvList_CellValueChanged;
            this.dgvList.SelectionChanged += dgvList_SelectionChanged;
        }


        /// <summary>
        /// 修改数值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void b_modify_Click(object sender, EventArgs e)
        {
            if (currentitem != null && this.dgvList.CurrentRow != null)
            {
                if (this.dgvList.CurrentRow.Index >= currentitem.dis.Count) return;
                int rowindex = this.dgvList.CurrentRow.Index;
                this.tb_Data.Text = this.tb_Data.Text.Replace(" ", "").Replace(",", "");
                this.dgvList.Rows[rowindex].Cells[0].Value = this.tb_DI.Text;
                this.dgvList.Rows[rowindex].Cells[1].Value = this.tb_Len.Text;
                this.dgvList.Rows[rowindex].Cells[2].Value = this.tb_type.Text;
                this.dgvList.Rows[rowindex].Cells[3].Value = this.tb_Data.Text;
                this.dgvList.Rows[rowindex].Cells[4].Value = this.tb_Name.Text;

            }
        }


        private void b_add_Click(object sender, EventArgs e)
        {
            try
            {
                Didata di = new Didata();
                this.tb_Data.Text = this.tb_Data.Text.Replace(" ", "").Replace(",", "");
                di.ChangeValue(DIITEMTYPE.DI_TYPE, tb_DI.Text,currentitem.meterType);
                di.ChangeValue(DIITEMTYPE.LEN_TYPE, tb_Len.Text,currentitem.meterType);
                di.ChangeValue(DIITEMTYPE.TYPE_TYPE, tb_type.Text,currentitem.meterType);
                di.ChangeValue(DIITEMTYPE.DATA_TYPE, tb_Data.Text,currentitem.meterType);
                di.ChangeValue(DIITEMTYPE.NAME_TYPE, tb_Name.Text,currentitem.meterType);

                foreach (Didata d in currentitem.dis)
                {
                    if (d.DI == di.DI)
                    {
                        MessageBox.Show("数据标志已经存在");
                        return;
                    }
                }

                this.currentitem.dis.Add(di);
                int index = this.dgvList.Rows.Add();
                dgvList.Rows[index].Cells[0].Value = ((currentitem.meterType == MeterType.Meter07) ? di.DI32String : di.DI16String);
                dgvList.Rows[index].Cells[1].Value = di.LenString;
                dgvList.Rows[index].Cells[2].Value = di.DataTypeString;
                dgvList.Rows[index].Cells[3].Value = di.DataString;
                dgvList.Rows[index].Cells[4].Value = di.Name;
                di.SN = (UInt16)(index+1);

                cfg.SaveDiData(currentitem, di,di, Config.optype.Add);


            }
            catch (System.Exception ex)
            {

            }
        }

        private void b_delete_Click(object sender, EventArgs e)
        {
            if (currentitem != null && this.dgvList.CurrentRow != null)
            {
                if (this.dgvList.CurrentRow.Index >= currentitem.dis.Count) return;
                int rowindex = this.dgvList.CurrentRow.Index;
                dgvList.Rows.RemoveAt(rowindex);
                cfg.SaveDiData(currentitem,currentitem.dis[rowindex],null, Config.optype.Delete);
                currentitem.dis.RemoveAt(rowindex);

            }
        }

        private void tb_meters_TextChanged(object sender, EventArgs e)
        {
            String[] ms = this.tb_meters.Text.Replace(" ", "").Split(',');

            if (ms.Length == 0||(ms.Length ==1 && ms[0]=="")) { currentitem.mlist.Clear(); this.tb_meters.Clear(); }

            List<String> old = currentitem.mlist;
            List<String> newlist = new List<String>();
            try
            {
                foreach (String s in ms)
                {
                    try
                    {
                        UInt64.Parse(s, System.Globalization.NumberStyles.HexNumber);
                        newlist.Add(s);
                    }

                    catch { }

                }
                //成功
                currentitem.mlist = newlist;
                cfg.SaveMeters(currentitem, newlist);
                return;

            }
            catch (Exception ex)
            {
                currentitem.mlist = old;
                this.tb_meters.Clear();
                 foreach (string l in currentitem.mlist) { this.tb_meters.AppendText(" " + l + ","); }               
            } 
            
        }



    }
}
